package com.utils;

import java.util.HashMap;
import java.util.Map;

/** 将{BG=/img/BG.jpg,logo=/img/logo.jpg}格式（也就是Map的toString方法的输出，','后没有空格） 的字符串转换为map的工具类 */
public class MapParser {
  /**
   * 将{BG=/img/BG.jpg,logo=/img/logo.jpg}格式（也就是Map的toString方法的输出，','后没有空格） 的字符串转换为map
   *
   * @param src 源字符串（若格式不符合说明则会转换错误)
   * @return 返回转换后的Map
   */
  public static Map<String, String> parse(String src) {
    HashMap<String, String> result = new HashMap<>();

    String KVSplit = "=";
    String itemSplit = ",";

    int len = src.length();
    int KVSplitIndex, itemSplitIndex = 0;
    String key;
    String value;
    while (itemSplitIndex != -1) {
      KVSplitIndex = src.indexOf(KVSplit, itemSplitIndex);
      if (KVSplitIndex == -1) {
        break;
      }
      key = src.substring(itemSplitIndex + 1, KVSplitIndex);

      itemSplitIndex = src.indexOf(itemSplit, KVSplitIndex);

      if (itemSplitIndex == -1) {
        value = src.substring(KVSplitIndex + 1, src.length() - 1);
      } else {
        value = src.substring(KVSplitIndex + 1, itemSplitIndex);
      }
      result.put(key, value);
    }
    return result;
  }
}
